package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.dao.StudentRepository;
import cn.edu.ctbu.dp01.entity.student;
import cn.edu.ctbu.dp01.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentService {
    @Autowired
    public StudentRepository studentRepository;

    /*
     * 添加学生
     * @return List<student>
     */

    public List<student> getAll() {
        return studentRepository.findAll();
    }

    /*
     * 根据ID查询学生
     * @param id 学生ID 主键，整数
     * @return student
     */

    public student getById(Integer id) {

        return studentRepository.findById(id).orElse(null);
    }

    /*
     * 根据姓名查询学生
     * @param name 学生姓名 字符串
     * @return List<student>
     */

    public List<student> findByName(String name) {
        return studentRepository.findByNameLike(name);
    }

    /*
     * 根据姓名和密码查询学生
     * @param name 学生姓名 字符串
     * @param password 学生密码 字符串
     * @return List<student>
     */

    public void insert(student student) {
        studentRepository.save(student);
    }

    public student update(student student) {
        return studentRepository.save(student);
    }

    @Transactional
    public student validateUsernameAndPassword(String sno, String password) throws Exception {
        List<student> students = studentRepository.findBySno(sno);

        if (students.size() > 0) {
            // 暂不处理加密逻辑
            student student = students.get(0);
            if (student.getPassword().equals(password)) {
                // 登录成功
                return student;
            } else {
                throw new RException(REnum.LOGIN_ERR);
            }
        } else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    @Transactional
    public void deleteBatch(List<Integer> ids) {
        studentRepository.deleteAllById(ids);
    }

    /*
     * 添加学生
     * @param student 学生对象
     * @return student
     */
    public student add(student student){
        return studentRepository.save(student);
    }

    public student delete(Integer id) {
        studentRepository.deleteById(id);
        return null;
    }

    public Page<student> getAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    public Page<student> getAll(Example<student> example, Pageable pageable) {
        return studentRepository.findAll(example, pageable);
    }


}
